/*
 * 作者		www.TheWk.cn.vc
 * 开发环境	Windows7 64位 MyEclipse8.6 JDK1.6.0_37
 * 开发日期	2013-11-13
 */
package common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

/**
 * 读取环境变量
 * 
 * @author xuan
 * 
 */
public abstract class ReadEnvUtils {

	public static Properties getEnvVars() throws Throwable {
		Process p = null;
		Properties envVars = new Properties();
		Runtime r = Runtime.getRuntime();
		String OS = System.getProperty("os.name").toLowerCase();
		if (OS.indexOf("windows 9") > -1) {
			p = r.exec("command.com /c set");
		} else if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 20") > -1)
				|| (OS.indexOf("windows xp") > -1) || OS.startsWith("windows")) {
			p = r.exec("cmd.exe /c set");
		} else {
			p = r.exec("env");
		}
		BufferedReader br = new BufferedReader(new InputStreamReader(
				p.getInputStream()));
		String line;
		while ((line = br.readLine()) != null) {
			int idx = line.indexOf('=');
			String key = line.substring(0, idx);
			String value = line.substring(idx + 1);
			envVars.setProperty(key, value);
			if("union_task_switch".equalsIgnoreCase(key)){
				System.out.println(key + " = " + value);
			}
		}
		return envVars;
	}
	
	/**
	 * 根据key读取环境变量值
	 * @param name
	 * @return
	 */
	public static String readEnvValue(String name){
		String value = "";
		try {
			Properties p = ReadEnvUtils.getEnvVars();
			value = p.getProperty(name);
		} catch (Throwable e) {
			e.printStackTrace();
		}
		if(StringUtils.isNotBlank(value)) value = value.trim();
		return value;
	}
	/**
	 * 直接使用java的getenv方法获取环境变量
	 * @param name
	 * @return
	 */
	public static String readEnvValueByJavaApi(String name){
		Map<String, String> map = System.getenv();
		if(map != null && map.size() >0){
			for(String key : map.keySet()){
				if(key.equalsIgnoreCase(name)){
					String value = map.get(key);
					if(StringUtils.isNotBlank(value)) value = value.trim();
					return value;
				}
			}
		}
		return null;
	}

	public static void main(String args[]) {
		try {
			Properties p = ReadEnvUtils.getEnvVars();
			System.out.println("the current value of union_task_switch is : "
					+ p.getProperty("union_task_switch"));
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

}
